/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aaa;

import XML.DigesterMarriesLucene;
import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;
import org.apache.lucene.index.IndexReader;
import org.xml.sax.SAXException;
import plist.PlistParser;
/**
 *
 * @author Bashev
 */
public class Advanced extends javax.swing.JFrame {
    private final Advanced adv;
    private String XMLFileName;
    private IndexReader ir;

    /**
     * Creates new form Advanced
     */
    public Advanced() {
        initComponents();
        this.setTitle("Advanced Export");
        Image im = null;
        try {
            im = ImageIO.read(this.getClass().getResource("/resources/HP-MSN.png"));
        } catch (IOException ex) {
            Logger.getLogger(Advanced.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setIconImage(im);
        adv = this;
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);        
        this.addWindowListener(new WindowListener() {

            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                adv.setVisible(false);
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblXML = new javax.swing.JLabel();
        txtXMLFile = new javax.swing.JTextField();
        btnChooseXMLFile = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        lblSaveAs = new javax.swing.JLabel();
        txtSaveAs = new javax.swing.JTextField();
        btnTable = new javax.swing.JButton();
        btnExcelFIle = new javax.swing.JButton();
        btnCSVFile = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblXML.setText("File:");

        btnChooseXMLFile.setText("...");
        btnChooseXMLFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseXMLFileActionPerformed(evt);
            }
        });

        btnSave.setText("Start");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        lblSaveAs.setText("Save As:");

        btnTable.setText("Table");
        btnTable.setEnabled(false);
        btnTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTableActionPerformed(evt);
            }
        });

        btnExcelFIle.setText("Excel File");
        btnExcelFIle.setEnabled(false);
        btnExcelFIle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcelFIleActionPerformed(evt);
            }
        });

        btnCSVFile.setText("CSV File");
        btnCSVFile.setEnabled(false);
        btnCSVFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCSVFileActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        jLabel1.setText("If you want to parse another language, choose the corresponding strings.xml ");

        jLabel2.setText("file and select a file name for the output.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnTable)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExcelFIle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCSVFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblSaveAs)
                                    .addComponent(lblXML))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtSaveAs, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
                                    .addComponent(txtXMLFile))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnChooseXMLFile, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblXML)
                    .addComponent(txtXMLFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnChooseXMLFile))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSaveAs)
                    .addComponent(txtSaveAs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnTable)
                    .addComponent(btnExcelFIle)
                    .addComponent(btnCSVFile)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnChooseXMLFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseXMLFileActionPerformed
        FileSystemView filesys = FileSystemView.getFileSystemView();
        String desktopPath = filesys.getHomeDirectory().getPath();
        JFileChooser fileChooserForm = new JFileChooser(desktopPath);
        fileChooserForm.setVisible(rootPaneCheckingEnabled);
        fileChooserForm.setFileFilter(new javax.swing.filechooser.FileFilter() {

           @Override
            public boolean accept(File f) {
                String filename = f.getName();
                return filename.endsWith(".strings") || filename.endsWith(".xml") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "*.xml, *.strings";
            }
        });
        int retVal = fileChooserForm.showOpenDialog(this);
        if (retVal == JFileChooser.APPROVE_OPTION) {
            txtXMLFile.setText(fileChooserForm.getSelectedFile().getPath());
            XMLFileName = MainForm.getFileNameWithoutExtension(fileChooserForm.getSelectedFile());
        }
    }//GEN-LAST:event_btnChooseXMLFileActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (!"".equals(txtXMLFile.getText()) && !"".equals(txtSaveAs.getText())) {
            parseXML();
            btnCSVFile.setEnabled(true);
            btnExcelFIle.setEnabled(true);
            btnTable.setEnabled(true);
            JOptionPane.showMessageDialog(this, "Operation executed!", "Info!", JOptionPane.WARNING_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Please fill the fields!", "Warning!", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void parseXML(){
        File f = new File(txtXMLFile.getText());
        try {
            if (txtXMLFile.getText().endsWith(".xml"))
                ir = DigesterMarriesLucene.parse(f, txtSaveAs.getText());
            else {
                PlistParser pp = new PlistParser();
                pp.parseP(txtXMLFile.getText());
                ir = pp.write(txtSaveAs.getText());
            }
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
    
    private void btnTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTableActionPerformed
        Results res;
        parseXML();
        try {
            String application = "";
            File f = new File(txtXMLFile.getText());
            if (txtXMLFile.getText().endsWith(".xml"))
                application = "Android - " + f.getName();
            else
                application = "Apple - " + f.getName();
            res = new Results(ir, application);
            res.setVisible(true);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnTableActionPerformed

    private void btnExcelFIleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcelFIleActionPerformed
        File f = null;        
        try {
            f = new File(Configurator.getConfigProperty("xls_path") + "//" + txtSaveAs.getText() + ".xls");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        MainForm.openFile(f);
    }//GEN-LAST:event_btnExcelFIleActionPerformed

    private void btnCSVFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCSVFileActionPerformed
        File f = null;        
        try {
            f = new File(Configurator.getConfigProperty("xls_path") + "//" + txtSaveAs.getText() + ".csv");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        MainForm.openFile(f);
    }//GEN-LAST:event_btnCSVFileActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Advanced.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Advanced.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Advanced.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Advanced.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Advanced().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCSVFile;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnChooseXMLFile;
    private javax.swing.JButton btnExcelFIle;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblSaveAs;
    private javax.swing.JLabel lblXML;
    private javax.swing.JTextField txtSaveAs;
    private javax.swing.JTextField txtXMLFile;
    // End of variables declaration//GEN-END:variables
}
